package com.lzh.thread;

import com.alibaba.ttl.TtlRunnable;

import java.util.Objects;
import java.util.concurrent.*;

/**
 * @author zhehen.lu
 * @date 2025/8/13 21:04
 */
public class LzhThreadExecutor extends ThreadPoolExecutor {
    private final ThreadDecorator threadDecorator;

    public LzhThreadExecutor(long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, String threadName, RejectedExecutionHandler handler) {
        this(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() << 1, keepAliveTime, unit, workQueue, threadName, handler);
    }

    public LzhThreadExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, String threadName, RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, new LzhThreadFactory(threadName), (ThreadDecorator)null, handler);
    }

    public LzhThreadExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, ThreadDecorator threadDecorator, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
        this.threadDecorator = threadDecorator;
    }

    @Override
    public void execute(Runnable command) {
        if (Objects.nonNull(this.threadDecorator)) {
            command = this.threadDecorator.decorate(command);
        }

        Runnable ttlRunnable = TtlRunnable.get(command);
        super.execute(ttlRunnable);
    }

    public static ScheduledThreadPoolExecutor createScheduledThreadPoolExecutor(int coreSize, String threadName) {
        return new ScheduledThreadPoolExecutor(coreSize, new LzhThreadFactory(threadName));
    }
}
